﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.Diagnostics;
using Microsoft.Win32;

namespace KengeeIT_ShopApp
{
    public partial class FrmLogin : Form
    {
        public FrmLogin()
        {
            InitializeComponent();
            SetAutoRun("KengeeIT_ShopApp", Application.ExecutablePath);
        }

        public bool SetAutoRun(string keyName, string filePath)
        {
            bool result = false;
            try
            {
                RegistryKey rkSOFTWARE = Registry.CurrentUser.OpenSubKey("SOFTWARE");
                RegistryKey rkMicrosoft =rkSOFTWARE.OpenSubKey("Microsoft");
                RegistryKey rkWindows = rkMicrosoft.OpenSubKey("Windows");
                RegistryKey rkCurrentVersion = rkWindows.OpenSubKey("CurrentVersion");
                RegistryKey rkRun = rkCurrentVersion.OpenSubKey("Run", true);
                rkRun.SetValue(keyName, filePath);
                rkRun.Close();
                result = true;
            }
            catch(Exception ex)
            {
                MessageBox.Show("function=SetAutoRun;\r\nkeyName=" + keyName + ";\r\nfilePath=" + filePath + ";\r\n" + ex.ToString());
            }
            return true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            lblVersion.Text = "(Version：" + Application.ProductVersion + ")";
            gbLogin.Visible = false;
            gbLogin.Enabled = false;
            gbLogin.Location = gbLink.Location;
            this.Width = 16 + gbLink.Width + 20;
            tbServerIP.Text = GetServerIPFromReg();
        }

        private void btnLinkServer_Click(object sender, EventArgs e)
        //连接服务器
        {
            lblLinkState.Text = "状态信息：正在尝试连接服务器...";
            if (tbServerIP.Text.Trim().Length == 0)
            {
                tbServerIP.Focus();
                lblLinkState.Text = "状态信息：服务器IP地址不能为空";
                lblLinkState.ForeColor = Color.Red;
            }
            else
            {
                try
                {
                    scKengee_IT_MIS.ConnectionString = @"Initial Catalog=kengee_it_mis;Persist Security Info=false;
                                                                  User ID=kengee_it;Password=f240cfcf0ab92d8ecb499e73a869e495;
                                                                  Data Source=" + tbServerIP.Text;
                    scKengee_IT_MIS.Open();
                    scKengee_IT_MIS.Close();
                    lblLinkState.Text = "状态信息：服务器连接成功";
                    lblLinkState.ForeColor = Color.Blue;
                    SetServerIP2Reg();
                    //AutoUpdate();//自动升级

                }
                catch (Exception ex)
                {
                    MessageBox.Show("服务器连接失败，请确认服务器IP地址!相关信息如下：\n" + ex.Message);
                    lblStateHint.Text = @"状态提示：服务器联系失败，但仍然可以登陆！";
                    lblStateHint.ForeColor = Color.Red;
                }
                finally
                {
                    btnOKLogin.PerformClick();
                }
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        //登录账号
        {
            this.Hide();
            KengeeIT_ShopApp_Main.FrmShopAppMain fsam = new KengeeIT_ShopApp_Main.FrmShopAppMain(scKengee_IT_MIS);
            fsam.ShowDialog();
            this.Show();
            fsam.Dispose();
        }

        private void tbUserName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(e.KeyChar==13)
            {
                tbPassword.Focus();
                tbPassword.SelectAll();
            }
        }

        private void tbPassword_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                btnLogin.PerformClick();
            }
        }

        private void tbServerIP_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                btnLinkServer.PerformClick();
            }
        }

        private void AutoUpdate()
        {
            string sql = @"select ID,FileName,Version,MD5 from ProgramFile where ProjectName='ShopApp'";
            SqlDataAdapter sdaProgramFiles = new SqlDataAdapter(sql, scKengee_IT_MIS);
            DataTable dtProgramFiles = new DataTable();
            scKengee_IT_MIS.Open();
            sdaProgramFiles.Fill(dtProgramFiles);
            scKengee_IT_MIS.Close();
            sdaProgramFiles.Dispose();

            string CurrentPath = Path.GetDirectoryName(Application.ExecutablePath) + "\\";
            for (int i = 0; i < dtProgramFiles.Rows.Count; i++)
            {
                string DBFileName = dtProgramFiles.Rows[i]["FileName"].ToString();
                string DBVersion = dtProgramFiles.Rows[i]["Version"].ToString();
                string DBMD5 = dtProgramFiles.Rows[i]["MD5"].ToString();
                string FilePath = CurrentPath + DBFileName;

                if (File.Exists(FilePath))
                {
                    FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(FilePath);
                    if (fvi.FileVersion.Equals(DBVersion) == false)
                    {
                        string NewMD5 = string.Empty;
                        while (NewMD5 != DBMD5)
                        {
                            File.Delete(FilePath);
                            FileOutput(FilePath);
                            NewMD5 = md5_hash(FilePath);
                        }
                        string ExtName = Path.GetExtension(FilePath);
                        if (ExtName.Equals(".upp"))
                        {
                            Process p = new Process();
                            p.StartInfo.FileName = CurrentPath + "UpdateProgram.exe";
                            p.StartInfo.Arguments = "KengeeIT_ShopApp.exe";
                            p.Start(); //启动
                            Application.Exit();
                        }
                    }
                }
                else
                {
                    string NewMD5 = string.Empty;
                    while (NewMD5 != DBMD5)
                    {
                        FileOutput(FilePath);
                        NewMD5 = md5_hash(FilePath);
                    }
                }
                pbAutoUpdate.Value = i * 100 / dtProgramFiles.Rows.Count;
            }
        }

        private void FileOutput(string aFilePath)
        {
            byte[] buffer;
            string FileName = System.IO.Path.GetFileName(aFilePath);
            SqlCommand cmd = scKengee_IT_MIS.CreateCommand();
            cmd.CommandText = "SELECT FileContent FROM ProgramFile where  (ProjectName='ShopApp') and (FileName='" + FileName + "')";
            scKengee_IT_MIS.Open();
            buffer = (byte[])cmd.ExecuteScalar(); //从数据库中取到的Image类型的字段的值，转换成byte[]类型
            scKengee_IT_MIS.Close();
            File.WriteAllBytes(aFilePath, buffer);
        }

        public string md5_hash(string path)
        {
            try
            {
                FileStream get_file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] hash_byte = get_md5.ComputeHash(get_file);
                string resule = System.BitConverter.ToString(hash_byte);
                resule = resule.Replace("-", "");
                return resule;
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }

        public string GetServerIPFromReg()
        {
            string result = string.Empty;
            RegistryKey rkCurrentUser = Registry.CurrentUser;
            RegistryKey rkSoftware = rkCurrentUser.OpenSubKey("Software");
            RegistryKey rkKengeeIT = rkSoftware.OpenSubKey("KengeeIT");
            if (rkKengeeIT != null)
            {
                result = rkKengeeIT.GetValue("ServerIP").ToString();
            }
            return result;
        }

        public void SetServerIP2Reg()
        {
            string result = string.Empty;
            RegistryKey rkCurrentUser = Registry.CurrentUser;
            RegistryKey rkSoftware = rkCurrentUser.OpenSubKey("Software",true);
            RegistryKey rkKengeeIT = rkSoftware.CreateSubKey("KengeeIT");
            rkKengeeIT.SetValue("ServerIP", tbServerIP.Text);
        }

        private void btnOKLogin_Click(object sender, EventArgs e)
        {
            this.Hide();
            KengeeIT_ShopApp_Main.FrmShopAppMain fsam = new KengeeIT_ShopApp_Main.FrmShopAppMain(scKengee_IT_MIS);
            fsam.ShowDialog();
            this.Show();
            fsam.Dispose();    
        }
    }
}
